package ru.stepanovdn.trading.loader

import jakarta.persistence.Persistence
import ru.tinkoff.piapi.contract.v1.InstrumentStatus
import ru.tinkoff.piapi.contract.v1.Share
import ru.tinkoff.piapi.core.InvestApi
import java.time.Instant
import java.time.ZoneId


fun main() {
    Class.forName("org.postgresql.Driver");

    /** https://investfunds.ru/stocks-leaders/turnover/ **/
    var token = System.getenv("token")
    var api = InvestApi.create(token);

    var sharesCF = api.instrumentsService.getShares(InstrumentStatus.INSTRUMENT_STATUS_BASE)
    val sharesDto = sharesCF.get()
    val rubSharesDto = sharesDto.asSequence().filter { share: Share -> share.currency == "rub" }
        .filter { share: Share ->  share.apiTradeAvailableFlag}
        .filter { share: Share -> share.ticker in Constants.tickers }
        .filter { share: Share -> share.classCode == "TQBR"}
        .filter { share: Share -> share.apiTradeAvailableFlag }.toList()

    print("Количество инструментов: " + rubSharesDto.size + "\n")
    rubSharesDto.forEach { share: Share? -> print("\n\n"+share+"\n\n"); }

    val shares = rubSharesDto.map { s: Share ->

        val first1MinCandleDate = s.first1MinCandleDate

        val ldt1 = Instant.ofEpochSecond( first1MinCandleDate.seconds, first1MinCandleDate.nanos.toLong() )
            .atZone( ZoneId.of( "Europe/Moscow" ) )
            .toLocalDateTime()

        val first1DayCandleDate = s.first1DayCandleDate

        val ldt2 = Instant.ofEpochSecond( first1DayCandleDate.seconds, first1DayCandleDate.nanos.toLong() )
            .atZone( ZoneId.of( "Europe/Moscow" ) )
            .toLocalDateTime()

        val share = ru.stepanovdn.trading.loader.entity.Share(
            isin = s.isin, figi = s.figi, ticker = s.ticker,
            classCode = s.classCode, lot = s.lot, currency = s.currency,
            exchange = s.exchange, sector = s.sector, apiTradeAvailableFlag = s.apiTradeAvailableFlag,
            forQualInvestorFlag = s.forQualInvestorFlag, nominalUnit = s.nominal.units,
            nominalNano = s.nominal.nano, buyAvailableFlag = s.buyAvailableFlag,
            sellAvailableFlag = s.sellAvailableFlag, minPriceIncrementUnit = s.minPriceIncrement.units,
            minPriceIncrementNano = s.minPriceIncrement.nano, first1minCandleDate = ldt1,
            first1dayCandleDate = ldt2, weekendFlag = s.weekendFlag, liquidityFlag = s.liquidityFlag
        )
        share.name = s.name
        share
    }

    val entityManagerFactory = Persistence.createEntityManagerFactory("default")
    val em = entityManagerFactory.createEntityManager()
    em.transaction.begin()
    shares.forEach { em.merge(it) }
    em.transaction.commit()
    em.close()
    entityManagerFactory.close()

    /** https://habr.com/ru/companies/haulmont/articles/572574/
     * https://blog.jetbrains.com/idea/2021/02/creating-a-simple-jpa-application/
     * */
}